#
# The MIT License
#
# Copyright (c) 2008 Nicholas Galbreath
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

import os
import os.path
import stat
import sys
from urlparse import urlparse

import boto
from boto.s3.connection import S3Connection

from progress_monitor import ProgressMonitor

def isdir(path):
    try:
        mode = os.stat(path)[stat.ST_MODE]
        return stat.S_ISDIR(mode)
    except OSError:
        return False

def isfile(path):
    try:
        return os.access(path, os.F_OK)
    except OSError:
        return False

def removefile(path):
    try:
        os.unlink(path)
    except:
        pass

def s3_download(s3file, localfile, force=False):
    """
    s3file must be in 'url' format:  s3://bucket/key
    localfile may be None, a directory, or a new filename
    force means overwrite.
    """

    if s3file.startswith('s3:/'):
        filefromparts = urlparse(s3file.replace('s3', 'http'))
    else:
        # TBD
        pass

    bucketname    = filefromparts[1]
    fullfile  = filefromparts[2]
    directory,filepart = os.path.split(fullfile)
    
    con = S3Connection()
    bucket = con.get_bucket(bucketname)
    akey = bucket.get_key(fullfile.strip('/'))
    
    if localfile is None:
        localfile = filepart
    elif isdir(localfile):
        localfile = localfile + '/' + filepart
    else:
        # file the way it is
        pass
    
    if not force and isfile(localfile):
        sys.stderr.write("Skipping %s since it exists\n" % (localfile,))
        return

    try:
        #sys.stderr.write("Copying %s to %s\n" % (s3file, localfile))

        localdir,lfile =  os.path.split(fullfile)
        p = ProgressMonitor(lfile)
        akey.get_contents_to_filename(localfile, cb=p.update, num_cb=1000)
        sys.stderr.write("\n")
    except KeyboardInterrupt:
        sys.stderr.write("\nRemoving %s\n" % localfile)
        removefile(localfile)
        sys.stderr.write("Aborting....\n")
        sys.exit(1)
    except Exception, e:
        sys.stderr.write("\nRemoving %s\n" % localfile)
        removefile(localfile)
        sys.stderr.write("%s failed with %s\n" % (localfile, str(e)))
